package com.xiaohao.ctdemo.controller;

import com.mathworks.toolbox.javabuilder.MWException;
import com.xiaohao.ctdemo.bean.Image;
import com.xiaohao.ctdemo.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 *
 * @author 小浩
 * @date 2018-07-22 09:52
 * @package com.xiaohao.ctdemo.controller
 * @description
 */
@RestController
@RequestMapping("/ctimage")
public class ImageController {
    @Autowired
    ImageService imageService;

    @RequestMapping("/image/{id}")
    public List<Image> getCTImageInfo(@PathVariable("id") int id) {
        try {
            return imageService.getImageInfo(id);
        } catch (MWException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return null;
    }

    @RequestMapping("/imagecode")
    public void getImageCode(HttpServletRequest request, HttpServletResponse response) {
        BufferedImage bufferedImage = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);
        Graphics graphics = bufferedImage.getGraphics();
        Color color = new Color(200, 150, 255);
        graphics.setColor(color);
        graphics.fillRect(0, 0, 68, 22);
        char[] ch = "QWERTYUIOPLKJHGFDSAZXCVBNM123456789".toCharArray();
        Random random = new Random();
        int len = ch.length, index;
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            index = random.nextInt(len);
            graphics.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));
            graphics.drawString(ch[index] + "", (i * 15) + 3, 18);
            stringBuffer.append(ch[index]);
        }

        request.getSession().setAttribute("code", stringBuffer.toString());
        ;
        try {
            ImageIO.write(bufferedImage, "JPG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
